﻿using System;
using System.Windows.Input;

namespace HBCode.Presentation.Command
{
    public class DelegateCommand : ICommand
    {
        private readonly Action executeMethod = delegate { };

        private readonly Func<bool> canExecuteMethod;

        public DelegateCommand(Action executeMethod) : this(executeMethod, null) { }

        public DelegateCommand(Action executeMethod, Func<bool> canExecuteMethod)
        {
            this.executeMethod = executeMethod;
            this.canExecuteMethod = canExecuteMethod;
        }

        public bool CanExecute(object parameter) { return this.canExecuteMethod != null ? this.canExecuteMethod() : true; }

        public void Execute(object parameter) { this.executeMethod(); }

        public event EventHandler CanExecuteChanged
        {
            add { CommandManager.RequerySuggested += value; }
            remove { CommandManager.RequerySuggested -= value; }
        }
    }

    public class DelegateCommand<T> : ICommand
    {
        private readonly Action<T> executeMethod = delegate { };

        private readonly Func<T, bool> canExecuteMethod;

        public DelegateCommand(Action<T> executeMethod) : this(executeMethod, null) { }

        public DelegateCommand(Action<T> executeMethod, Func<T, bool> canExecuteMethod)
        {
            this.executeMethod = executeMethod;
            this.canExecuteMethod = canExecuteMethod;
        }

        public bool CanExecute(object parameter)
        {
            T tobj = (T)parameter;
            return this.canExecuteMethod != null ? this.canExecuteMethod(tobj) : true;
        }

        public void Execute(object parameter)
        {
            T tobj = (T)parameter;
            this.executeMethod(tobj);
        }

        public event EventHandler CanExecuteChanged
        {
            add { CommandManager.RequerySuggested += value; }
            remove { CommandManager.RequerySuggested -= value; }
        }
    }

}
